import { defineStore } from "pinia";
import { buyProducts, IProduct } from "../api/shop";
import { useProductsStore } from "./products";

// 购物车类型：新增数量：quantify，删除库存：inventory
type CartProduct = {
  quantify:number
} & Omit<IProduct,'inventory'>

export const useCartStore = defineStore('cart', {
  state: () => {
    return {
      cartProducts: [] as CartProduct[],
      checkoutStatus:null as null|string
    }
  },
  getters: {
    // 计算总价
    totalPrice(state) {
      return state.cartProducts.reduce((total,item) => {
        return Math.floor(total+item.price*item.quantify)
      },0)
    }
  },
  actions: {
    addProductToCart(product: IProduct) {
      if (product.inventory < 1) {
        return
      }
      //检查购物车是否有相应的数据
      const cartItem = this.cartProducts.find(item => item.id === product.id)
      if (cartItem) {
        cartItem.quantify++
      } else {
        this.cartProducts.push({
          id: product.id,
          title: product.title,
          price: product.price,
          quantify:1
        })
      }
      // 修改库存
      const products=useProductsStore()
      products.decrementProduct(product.id)
    },
    async chekout() {
      const ret=await buyProducts()
      this.checkoutStatus = ret ? '成功' : '失败'
      if (ret) {
        this.cartProducts=[]
      }
    }
  }
})